﻿using System.Web.UI.WebControls;

namespace ETestIT.UI.AppControls
{
    using System;
    using System.Collections.Generic;
    using System.Web.UI;
    using Core;
    using Core.Infrastructure;
    using SharpArch.Core.PersistenceSupport;

    public partial class CandidateAddUpdate : UserControl
    {
        public event EventHandler Save;
        IRepository<JobTitle> jobTitleRepository;
        private ListItem candidateCagoryItem;

        protected void Page_Load(object sender, EventArgs e)
        {
            jobTitleRepository = IoC.Resolve<IRepository<JobTitle>>();

            if (!IsPostBack)
            {
                ddlJobTitles.DataSource = jobTitleRepository.GetAll();
                ddlJobTitles.DataValueField = "Id";
                ddlJobTitles.DataTextField = "Name";
                ddlJobTitles.DataBind();
                foreach (Candidate.CandidateCategories c in Enum.GetValues(typeof(Candidate.CandidateCategories)))
                {
                    candidateCagoryItem = new ListItem(Enum.GetName(typeof(Candidate.CandidateCategories), c), c.ToString());
                    ddlCategories.Items.Add(candidateCagoryItem);
                }
            }
        }

        public void SetModel(Candidate candidate)
        {
            ddlJobTitles.SelectedValue = candidate.ProfileTitle.Id.ToString();
            tbFirstName.Text = candidate.FirstName;
            tbSurename.Text = candidate.Surename;
            ddlCategories.SelectedValue = candidate.Category.ToString();
            tbPhone.Text = candidate.Phone;
            tbEmail.Text = candidate.Email;
        }

        public void UpdateModel(Candidate candidate)
        {
            var selectedValue = int.Parse(ddlJobTitles.SelectedValue);
            var titles = new List<JobTitle>(jobTitleRepository.GetAll());

            candidate.ProfileTitle = titles.Find(title => title.Id.Equals(selectedValue));
            candidate.FirstName = tbFirstName.Text.Trim();
            candidate.Surename = tbSurename.Text.Trim();
            candidate.Category =
                (Candidate.CandidateCategories)
                Enum.Parse(typeof (Candidate.CandidateCategories), ddlCategories.SelectedValue);
            candidate.Phone = tbPhone.Text.Trim();
            candidate.Email = tbEmail.Text.Trim();
        }

        protected void bntSave_Clicked(object sender, EventArgs e)
        {
            if (Save != null)
                Save(sender, e);
        }
    }
}